package com.gxa.pingan.service.impl;

import com.gxa.pingan.common.ExceptionCode;
import com.gxa.pingan.exception.BusinessException;
import com.gxa.pingan.mapper.ManagerMapper;
import com.gxa.pingan.pojo.Manager;
import com.gxa.pingan.service.ManagerService;
import com.gxa.pingan.utils.MD5Util;
import com.gxa.pingan.utils.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.List;

/**
 * @version fi
 * @Author lonny
 * @Date 2021/10/25 16:43
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ManagerServiceImpl implements ManagerService {

    @Resource
    private ManagerMapper managerMapper;

    /**
     * 判断手机和邮箱是否满足规范
     * 新增和修改的手机号邮箱号是否已经从讠
     *
     * @param manager 对象
     * @throws Exception 抛出
     */
    private void determination(Manager manager) throws Exception {
//        判断邮箱格式是否满足要求
        if (manager.getEmail() != null) {
            boolean email = StringUtils.isEmail(manager.getEmail());
            if (!email) {
                throw new BusinessException(ExceptionCode.EMAIL_ERROR);
            }
        }
//        判断手机号格式是否满足要求
        if (manager.getPhone() != null) {
            boolean phoneNumber = StringUtils.isPhoneNumber(manager.getPhone());
            if (!phoneNumber) {
                throw new BusinessException(ExceptionCode.PHONE_ERROR);
            }
        }
    }

    /**
     * 判断手机号和邮箱是否已经存在，更改的手机号和邮箱一致，也会提示已存在
     *
     * @param manager 对象
     * @throws Exception 抛出
     */
    private void beFrom(Manager manager) throws Exception {
        List<Manager> byPhoneOrEmail = managerMapper.findByPhoneOrEmail(manager.getPhone(), manager.getEmail());
        if (byPhoneOrEmail.size() >= 1) {
            for (Manager mng : byPhoneOrEmail) {
                if (mng.getId().equals(manager.getId())) {
                    System.out.println(mng.getId().equals(manager.getId()));
                    return;
                } else {
                    if (mng.getEmail().equals(manager.getEmail())) {
                        throw new BusinessException(ExceptionCode.DUPLICATE_EMAIL);
                    }
                    if (mng.getPhone().equals(manager.getPhone())) {
                        throw new BusinessException(ExceptionCode.REPEAT_PHONE);
                    }
                }
            }
        }
    }

    @Override
    public int updateManager(Manager manager) throws Exception {
        determination(manager);
        manager.setPassword(MD5Util.encode(manager.getPassword()));
        beFrom(manager);
        int i = managerMapper.updateManager(manager);

        if (i > 0) {
            return i;
        }
        throw new BusinessException(ExceptionCode.FAILED_OPERATION);
    }

    /**
     * 修改信息
     *
     * @param phone  电话
     * @param email  邮箱
     * @param newPwd 密码
     * @return 返回
     * @throws Exception 抛出
     */
    @Override
    public Manager Retrieve(String phone, String email, String newPwd) throws Exception {
        List<Manager> byPhoneOrEmail = managerMapper.findByPhoneOrEmail(phone, email);
        if (byPhoneOrEmail.size() > 0) {
            Manager manager = byPhoneOrEmail.get(0);
            manager.setPassword(MD5Util.encode(newPwd));
            manager.setPhone(phone);
            manager.setEmail(email);
            managerMapper.updateManager(manager);
            return manager;
        }
        throw new BusinessException(ExceptionCode.NO_USER);
    }

    /**
     * 获取数据数量
     *
     * @return 抛出
     */
    @Override
    public int size() {
        List<Manager> all = managerMapper.findAll(null, null);
        return all.size();

    }

    @Override
    public List<Manager> findAll(Integer page, Integer size) throws Exception {
        if (page == null) {
            return managerMapper.findAll(null, null);
        }
        if (page < 1) {
            throw new BusinessException(ExceptionCode.PAGE_ERROR);
        }
        return managerMapper.findAll((page - 1) * size, size);
    }

    @Override
    public Manager login(String phone, String password) throws Exception {
        Manager login = managerMapper.login(phone, MD5Util.encode(password));
        if (login != null) {
            if (login.getInUsed() != null && login.getInUsed()) {
                Timestamp lastTime = new Timestamp(System.currentTimeMillis());
                login.setLastTime(lastTime);
                managerMapper.updateManager(login);
                return login;
            }
            throw new BusinessException(ExceptionCode.EMAIL_LOGIN_USED);
        }
        throw new BusinessException(ExceptionCode.EMAIL_LOGIN);
    }

    @Override
    public int deleteManager(String ids) throws Exception {
        if (ids == null || ids.isEmpty()) {
            throw new BusinessException(ExceptionCode.PARAM_ERROR);
        }
        String[] id = ids.split(",");
        List<String> list = Arrays.asList(id);
        for (String s : list) {
            Manager manager = managerMapper.find(s);
            if (manager == null) {
                throw new BusinessException(ExceptionCode.NO_USER);
            }
        }
        return managerMapper.deleteManager(list);
    }

    @Override
    public void updateInUsed(Long id) throws Exception {
        int i = managerMapper.updateInUsed(id);
        if (i == 0) {
            throw new BusinessException(ExceptionCode.FAILED_OPERATION);
        }
    }


    @Override
    public int addManager(Manager manager) throws Exception {
        determination(manager);
        manager.setPassword(MD5Util.encode(manager.getPassword()));
        beFrom(manager);
        int i = managerMapper.addManager(manager);
        if (i > 0) {
            return i;
        }
        throw new BusinessException(ExceptionCode.FAILED_OPERATION);
    }
}
